//
//  KaidianViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/15.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "KaidianViewController.h"
#import "LCActionSheet.h"
#import "CityPickerView.h"
#import "JianjieViewController.h"
#import <MBProgressHUD.h>

#import "IWUploadParam.h"
#import "UserModel.h"
#import "ResMode.h"
#import "Puser.h"
#import "KaiDianSUSViewController.h"
#import  <AssetsLibrary/AssetsLibrary.h>
#import <QBImagePickerController/QBImagePickerController.h>

#import "SDPhotoBrowser.h"
#import "ShengfenShowViewController.h"
#import "Puser.h"
#define SCALEFlOALT 0.8


@interface KaidianViewController ()<LCActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CityPickerDelegate,QBImagePickerControllerDelegate,SDPhotoBrowserDelegate>
@property (weak, nonatomic) IBOutlet UITextField *truename;
@property (weak, nonatomic) IBOutlet UITextField *cardnumber;
@property (weak, nonatomic) IBOutlet UIButton *loacitonbtn;
@property (weak, nonatomic) IBOutlet UIButton *jianjiebtn;
@property (weak, nonatomic) IBOutlet UIButton *headpicbtn;
@property (weak, nonatomic) IBOutlet UIButton *photo1btn;
@property (weak, nonatomic) IBOutlet UIButton *photo2btn;
@property (weak, nonatomic) IBOutlet UIButton *photo3btn;
@property (weak, nonatomic) IBOutlet UIButton *photo4btn;
@property (weak, nonatomic) IBOutlet UIView *photoview;

@property (weak, nonatomic) IBOutlet UIButton *backbtn;
@property (weak, nonatomic) IBOutlet UIButton *followbtn;
@property (weak, nonatomic) IBOutlet UIButton *holderbtn;


@property (nonatomic,strong) UIImagePickerController *picker;
@property (nonatomic,copy) NSString *province;
@property (nonatomic,copy) NSString *city;
@property (nonatomic,copy) NSString *district;
@property (nonatomic,strong) CityPickerView *pickerview;
@property (nonatomic,strong) UUImageAvatarBrowser *brower;
@property (weak, nonatomic) IBOutlet UIView *headpicview;

@property (nonatomic,strong) NSArray *btnarray;
@property (nonatomic,strong) NSMutableArray *photoarray;
@property (nonatomic,strong) Puser *user;
@end

@implementation KaidianViewController

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(NSMutableArray *)photoarray{
    if ( _photoarray==nil) {
        _photoarray=[NSMutableArray array];
    }
    return  _photoarray;
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

-(NSArray *)btnarray{
 
    if (_btnarray==nil) {
        _btnarray=@[self.headpicbtn,self.photo1btn,self.photo2btn,self.photo3btn,self.photo4btn,self.backbtn,self.followbtn,self.holderbtn];
    }
    return _btnarray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title=@"个人认证";
    self.truename.text=self.user.user_truename;
}
- (IBAction)shili:(id)sender {
    
    ShengfenShowViewController *vc=[[ShengfenShowViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
-(void)citypicker:(NSString *)city{
    [self.loacitonbtn setTitle:city forState:UIControlStateNormal];
    [self.loacitonbtn setTitleColor:UIColorWithRGB(44, 44, 44) forState:UIControlStateNormal];
}
-(void)citypicker:(NSString *)procestr city:(NSString *)citystr dist:(NSString *)dist{
    self.province=procestr;
    self.city=citystr;
    self.district=dist;
    
}
-(CityPickerView *)pickerview{
    if (_pickerview==nil) {
        _pickerview=[[CityPickerView alloc]initWithDelegate:self WithColoum:3];
    }
    return _pickerview;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)picklocationclick:(id)sender {
    [self.truename endEditing:YES];
     [self.cardnumber endEditing:YES];
    [self.pickerview showinView:self.view];
}
- (IBAction)jianjieclick:(id)sender {
    JianjieViewController *jvc=[JianjieViewController viewcontroller];
    jvc.block=^(NSString *str){
        
        [self.jianjiebtn setTitleColor: UIColorWithRGB(44, 44, 44) forState:UIControlStateNormal];
        [self.jianjiebtn setTitle:str forState:UIControlStateNormal];
    };
    [self.navigationController pushViewController:jvc animated:YES];
    
}
- (IBAction)headpicclick:(UIButton *)sender {
    if (sender.isSelected) {
        [self showHasActionSheet:sender.tag];
    }else{
        [self showActionSheet:sender.tag];
    }
    
}

-(void)showHasActionSheet:(NSInteger)tag{
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:@[@"查看大图",@"重新上传",@"删除"] redButtonIndex:2 delegate:self];
    sheet.tag=tag;
    sheet.isTag=YES;
    [sheet show];
}
-(UIImagePickerController *)picker{
    if (_picker==nil) {
        _picker=[[UIImagePickerController alloc]init];
        _picker.view.backgroundColor = [UIColor orangeColor];
        
        _picker.delegate =self;
        _picker.allowsEditing = YES;
    }
    return _picker;
}

-(void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets{
    NSMutableArray *marray=[NSMutableArray array];
    UIButton *btn=self.btnarray[imagePickerController.view.tag];
    
    [self dismissViewControllerAnimated:YES completion:^{
        for (ALAsset *asset in assets) {
            
            UIImage *image=[UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
            [marray addObject:image];
            
        }
        if (btn.isSelected) {
            [btn setImage:marray[0] forState:UIControlStateSelected];
        }else{
            if (btn.tag==0||btn.tag>4) {
                [btn setImage:marray[0] forState:UIControlStateSelected];
                btn.selected=YES;
            }else{
                
                [self.photoarray addObjectsFromArray:marray];
                [self reloadImage];
            }
            
        }
    }];
    
}

-(void)showCarmera:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
    self.picker.view.tag=tag;
    self.picker.sourceType=sourcheType;
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)showImagePicker:(NSInteger)tag{
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.picker.sourceType=sourcheType;
    self.picker.view.tag=tag;
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)reloadImage{
    for (int i=0; i<4; i++) {
        UIButton *btn=self.btnarray[i+1];
        if (i<self.photoarray.count) {
            [btn setImage:self.photoarray[i] forState:UIControlStateSelected];
            btn.selected=YES;
            btn.hidden=NO;
        }else{
            btn.selected=NO;
            if (i==self.photoarray.count) {
                btn.hidden=NO;
            }else{
                btn.hidden=YES;
            }
        }
    }
}
-(void)showimage:(NSInteger)tag{
  
    [self showImageWith:tag-1];
    
}
-(void)showImageWith:(NSInteger)index{
    
    SDPhotoBrowser *browser=[[SDPhotoBrowser alloc]init];
    UIButton *btn=self.btnarray[index+1];
    browser.sourceImagesContainerView =index<0||index>=4?btn:self.photoview; // 原图的父控件
    browser.imageCount = index<0||index>=4?1:self.photoarray.count; // 图片总数
    browser.currentImageIndex = index<0||index>=4?0:index;
    browser.delegate = self;
    browser.tag=index;
    [browser show];
}


-(void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==actionSheet.btnCount-1) return;
    if (actionSheet.isTag) {
        switch (buttonIndex) {
            case 0:
                [self showimage:actionSheet.tag];
                
                break;
            case 1:
                [self showActionSheet:actionSheet.tag];
                break;
            case 2:
            {
                
                if (actionSheet.tag==0||actionSheet.tag==5||actionSheet.tag==6||actionSheet.tag==7) {
                 UIButton *btn = self.btnarray[actionSheet.tag];
                    btn.selected=NO;
                    [btn
                     setImage:nil forState:UIControlStateSelected];
                }else{
                    [self.photoarray removeObjectAtIndex:actionSheet.tag-1];
                    [self reloadImage];
                }
                
            }
                break;
            default:
                break;
        }
        
        
    }else{
        
        UIButton *btn=self.btnarray[actionSheet.tag];
        [self switchImagePickerOrActionsheet:btn.isSelected WithTag:actionSheet.tag index:buttonIndex];
    }
}

-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    if (browser.tag<0||browser.tag>=4) {
        UIButton *btn=self.btnarray[browser.tag+1];
        return btn.imageView.image;
    }else{
    return self.photoarray[index];
    }
}

-(BOOL)checkForm{
    if ([self.truename.text isEqualToString:@""]) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"请填写真实姓名";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
    
    if (self.cardnumber.text.length>0) {
        if(![NSString validateIdentityCard:self.cardnumber.text]){
            MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
            hud.labelText=@"请填写正确的身份证号";
            hud.mode = MBProgressHUDModeText;
            hud.margin = 10.f;
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
            return false;
        }
    }
    if (!self.province||!self.city||!self.district) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"请选择所在省市地区";
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        return false;
    }
//    if (!self.backbtn.isSelected) {
//        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//        hud.labelText=@"请上传身份证背面照";
//        hud.mode = MBProgressHUDModeText;
//        hud.margin = 10.f;
//        hud.removeFromSuperViewOnHide = YES;
//        [hud hide:YES afterDelay:1];
//        return false;
//    }
//    if (!self.followbtn.isSelected) {
//        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//        hud.labelText=@"请上传身份证正面照";
//        hud.mode = MBProgressHUDModeText;
//        hud.margin = 10.f;
//        hud.removeFromSuperViewOnHide = YES;
//        [hud hide:YES afterDelay:1];
//        return false;
//    }
//    if (!self.holderbtn.isSelected) {
//        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
//        hud.labelText=@"请上传手持身份证照";
//        hud.mode = MBProgressHUDModeText;
//        hud.margin = 10.f;
//        hud.removeFromSuperViewOnHide = YES;
//        [hud hide:YES afterDelay:1];
//        return false;
//    }
  return true;
}

-(void)switchImagePickerOrActionsheet:(BOOL)ishasimg WithTag:(NSInteger)tag index:(NSInteger)buttonindex{
    
    if (buttonindex==0) {
            [self showCarmera:tag];
        }else{
            UIButton *btn=self.btnarray[tag];
            
            QBImagePickerController *imagePickerController = [QBImagePickerController new];
            imagePickerController.view.tag=tag;
            imagePickerController.delegate = self;
            imagePickerController.allowsMultipleSelection = YES;
            if (btn.isSelected||tag==0||tag>4) {
                imagePickerController.maximumNumberOfSelection = 1;
            }else{
                
                imagePickerController.maximumNumberOfSelection = 4-self.photoarray.count;
            }
            imagePickerController.showsNumberOfSelectedAssets = YES;
            
            
            [self presentViewController:imagePickerController animated:YES completion:NULL];
        }

    
}
- (IBAction)upload:(id)sender {
    if([self checkForm]){
       
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"正在上传...";
        hud.mode = MBProgressHUDModeIndeterminate;
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        Puser *user=[Puser getUser];
        params[@"user_id"]=user.user_id;
        params[@"name"]=self.truename.text;
        if (self.cardnumber.text.length>0) {
             params[@"pnum"]=self.cardnumber.text;
        }
        params[@"province"]=self.province;
        params[@"city"]=self.city;
        params[@"district"]=self.district;
        if (![self.jianjiebtn.titleLabel.text isEqualToString:@"请输入个人简介"]) {
            params[@"intro"]=self.jianjiebtn.titleLabel.text;
        }
       NSMutableArray *photoarray=[NSMutableArray array];
        if (self.headpicbtn.isSelected) {
            IWUploadParam *headpicparam=[[IWUploadParam alloc]init];
            
            
            headpicparam.data=[[self.headpicbtn currentImage] compressData:[self.headpicbtn currentImage] toMaxFileSize:DefailutPicSize];
            headpicparam.mineType=@"jpeg";
            headpicparam.paramName=@"ico";
            headpicparam.fileName=@"ico.jpeg";
            NSLog(@"%ld",headpicparam.data.length);
            [photoarray addObject:headpicparam];
        }
       
       
        if (self.backbtn.isSelected) {
            IWUploadParam *backparam=[[IWUploadParam alloc]init];
            
            backparam.data=[[self.backbtn currentImage] compressData:[self.backbtn currentImage] toMaxFileSize:DefailutPicSize];
            backparam.mineType=@"jpeg";
            backparam.paramName=@"p_out";
            backparam.fileName=@"p_out.jpeg";
            [photoarray addObject:backparam];
        }
      
        if (self.followbtn.isSelected) {
            IWUploadParam *followparam=[[IWUploadParam alloc]init];
            followparam.data=[[self.followbtn currentImage] compressData:[self.followbtn currentImage] toMaxFileSize:DefailutPicSize];
            followparam.mineType=@"jpeg";
            followparam.paramName=@"p_zhen";
            followparam.fileName=@"p_zhen.jpeg";
            [photoarray addObject:followparam];

        }
        
        if (self.holderbtn.isSelected) {
            IWUploadParam *handwith=[[IWUploadParam alloc]init];
            handwith.data=[[self.holderbtn currentImage] compressData:[self.holderbtn currentImage] toMaxFileSize:DefailutPicSize];
            handwith.mineType=@"jpeg";
            handwith.paramName=@"p_width";
            handwith.fileName=@"p_width.jpeg";
            [photoarray addObject:handwith];
        }
        NSMutableArray *imgstrarray=[NSMutableArray array];
        
        if (self.photo1btn.isSelected) {
            NSData *imagedata=[UIImage compressData:[self.photo1btn currentImage] toMaxFileSize:DefailutPicSize];
            NSString *base64str=[imagedata imageBase64Data:imagedata];
            [imgstrarray addObject:base64str];
            
        }
        if (self.photo2btn.isSelected) {
            NSData *imagedata=[UIImage compressData:[self.photo2btn currentImage] toMaxFileSize:DefailutPicSize];
            NSString *base64str=[imagedata imageBase64Data:imagedata];
            [imgstrarray addObject:base64str];
        }

        if (self.photo3btn.isSelected) {
            NSData *imagedata=[UIImage compressData:[self.photo3btn currentImage] toMaxFileSize:DefailutPicSize];
            NSString *base64str=[imagedata imageBase64Data:imagedata];
            [imgstrarray addObject:base64str];
        }

        if (self.photo4btn.isSelected) {
            NSData *imagedata=[UIImage compressData:[self.photo4btn currentImage] toMaxFileSize:DefailutPicSize];
            NSString *base64str=[imagedata imageBase64Data:imagedata];
            [imgstrarray addObject:base64str];
        }
        
        if (imgstrarray.count>0) {
            params[@"shop_imgs"]=[NSString DataTOjsonString:imgstrarray];
        }
        
        
        
        
        [PostUitls upload:kaidianurl parameters:params uploadarray:photoarray success:^(id responseobj) {
            NSDictionary *dict=responseobj;
            ResMode *mode=[ResMode modeWithDict:dict];
            NSLog(@"%@",mode.msg);
            if ([mode.state integerValue]==400) {
                self.user.power=@(2);
                [Puser save];
                [self pushToSuS:mode];
            }
            [hud hide:YES];
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [hud hide:YES afterDelay:0.5];
        }];
 
    }
}
-(void)pushToSuS:(ResMode *)mode{
    KaiDianSUSViewController *ksvc=[KaiDianSUSViewController viewcontroller];
    
    [self.navigationController pushViewController:ksvc animated:YES];
}
-(void)showActionSheet:(NSInteger)tag{
    
    LCActionSheet *sheet=[[LCActionSheet alloc]initWithTitle:nil buttonTitles:@[@"拍照",@"从相册中选取"] redButtonIndex:-1 delegate:self];
    sheet.tag=tag;
    [sheet show];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [self dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
         UIButton *btn=self.btnarray[picker.view.tag];
        if (picker.view.tag==0||picker.view.tag>4) {
            btn.selected=YES;
            [btn setImage:image forState:UIControlStateSelected];
        }else{
           
            if (btn.isSelected) {
                [self.photoarray replaceObjectAtIndex:picker.view.tag-1 withObject:image];
            }else{
                [self.photoarray addObject:image];
            }
            [self reloadImage];
        }
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
